import React, { useState, useEffect,useRef } from "react";
import { MessageListProps,MessageItemProps } from "./type";
import { Avatar,Image } from "antd";
import { LoadingOutlined } from "@ant-design/icons";
import { MdPreview } from 'md-editor-rt';
import SimpleBar from 'simplebar-react';
import { useChatStore,useUserStore } from "@/store";
import { chat } from '@/apis'
import userAvatar from "./assets/images/user-avatar.png"
import assistantAvatar from "./assets/images/assistant-avatar.png"
import { scrollToBottom } from "./assets/js"
import 'md-editor-rt/lib/style.css';
import 'simplebar-react/dist/simplebar.min.css';
import "./index.css";

const MessageList: React.FC<MessageListProps> = (props: MessageListProps) => {
  const { messageList } = props
  const simpleBarRef = useRef<HTMLDivElement>(null)
  const onAnswerCreating = () => {
    scrollToBottom()
  }
  const scrollToBottom = () => {
    if (simpleBarRef.current) {
      const scrollElement = simpleBarRef.current.getScrollElement();
      scrollElement.scrollTop = scrollElement.scrollHeight;
    }
  }
  useEffect(() => {
    scrollToBottom()
  }, [messageList])
  return (
    <div className="c_message_list_wrapper">
        <SimpleBar style={{ height: '100%' }}  ref={simpleBarRef}>
          {messageList.map((item, index) => (
              <MessageItem key={item.id} data={item} onAnswerCreating={onAnswerCreating}/>
          ))}
        </SimpleBar>
    </div>
  );
};

// 消息项 <MdPreview id={markdownId} modelValue={randerContent} />
const MessageItem: React.FC<MessageItemProps> = (props: MessageItemProps) => {
  const {
    updateAnswerCreatingAction,
    currentConversation,
    updateCurrentConversationAction,
    getConversationListFetchAction
  } = useChatStore((state) => state)
  const fakeLoadingTime = 1000
  const { userInfo } = useUserStore((state) => state)
  const { role, message, question, isNewSend } = props.data;
  const [randerContent, setRanderContent] = useState(message)
  const [imageList, setImageList] = useState(message)
  const [isLoading, setIsLoading] = useState(isNewSend)
  const hasCreatedImage = useRef(false);
  const [markdownId] = useState('preview-only');
  const [answerMarkdownId] = useState('answer-preview-only');
    useEffect(() => {
      let ignore = false;
      let imgTimer = null
      if (isNewSend && role === "assistant" && !ignore) {
        setTimeout(() => {
          props.onAnswerCreating()
          if (props.data.sendType === 'image') {
            if (!hasCreatedImage.current) {
              hasCreatedImage.current = true;
              setIsLoading(true)
              chat.createImageFetch({
                message: question,
                conversationId: currentConversation.id
              }).then((res) => {
                // 轮询获取图片
                imgTimer = setInterval(() => {
                  setIsLoading(true)
                  chat.getImageTaskFetch({
                    taskId: res.output.task_id,
                    conversationId: currentConversation.id
                  }).then((result) => {
                    if (result.data.output.task_status === 'SUCCEEDED') {
                      clearInterval(imgTimer);
                      updateAnswerCreatingAction(false)
                      // 如果当前会话有loading状态，则更新会话列表
                      const isHasLoading = currentConversation.loading
                      if (isHasLoading) {
                        getConversationListFetchAction().then((list) => {
                          updateCurrentConversationAction(list[0] ? list[0] : {})
                        })
                      }
                      setIsLoading(false);
                      setImageList(result.data.output.results[0].url);
                    }
                  });
                }, 3000);
              });
            }
          } else {
            setIsLoading(false)
            // 获取聊天数据
            chat.getChatDataFetch({
              message: question,
              conversationId: currentConversation.id
            },async (content, done, type) => {
              setRanderContent(prevContent => `${prevContent}${content}`)
              props.onAnswerCreating()
              if (done) {
                updateAnswerCreatingAction(false)
                // 如果当前会话有loading状态，则更新会话列表
                const isHasLoading = currentConversation.loading
                if (isHasLoading) {
                  getConversationListFetchAction().then((list) => {
                    updateCurrentConversationAction(list[0] ? list[0] : {})
                  })
                }
              }
            })
          }
         
        }, fakeLoadingTime)
      }
      return () => {
        ignore = true;
      }
    }, [isNewSend, role])
  console.log(props,'props')
  return (
    <div className={`c_message_base_item ${role}`}>
      <Avatar src={role === "assistant" ? assistantAvatar : (userInfo?.avatar || userAvatar)} size={36}/>
      <div className="c_message_base_item_content">
        {role === "assistant" ? (
          isLoading ? <LoadingOutlined /> : 
            props.data.sendType == 'image' ? <Image width={400} src={imageList}></Image> : <MdPreview id={markdownId} modelValue={randerContent} />
        ) : (
          // <MdPreview id={answerMarkdownId} modelValue={message} />
          <span>{message}</span>
        )}
      </div>
    </div>
  );
};


export default MessageList;
